if (typeof CC === "undefined" || !CC) {
	var CC = {};
}

CC.comparisonTool = {
	query: {
		isin: '',
		startDate: '',
		endDate: '',
		dataType: '',
		i: 0
	},
	separateNavigator: {
		name: 'Navigator',
		data: []
	},
	series: [],
	seriesColorCount: 1,
	chart: {},
	defaultBaseline: 10000,
	defaultOptions: {
		chart: {
			backgroundColor: {
				linearGradient : {
					x1: 0,
					y1: 0,
					x2: 0,
					y2: 1
				},
				stops : [[0, '#ebeef0'], [0.5, 'rgba(255, 255, 255, 0)']]
			},
			borderRadius: 0,
			height: 600,
			renderTo: 'comparisonChartContainer',
			spacingBottom: 2,
			spacingLeft: 5,
			spacingRight: 5	
		},
		credits: {
			enabled: false
		},
		legend: {
			enabled: false
		},
		navigator: {
			adaptToUpdatedData: false
		},
		plotOptions: {
			series: { // default options for all chart types
				//compare: 'percent',
				showInLegend: false,
				marker: {
					states: {
						hover: {
							lineColor: null
						}
					},
					symbol: "circle"
				}
			}
		},
		scrollbar: {
			liveRedraw: false
		},
		tooltip: {
			backgroundColor: 'rgba(255, 255, 255, 0.9)',
			borderColor: '#484848',
			borderWidth: 1,
			useHTML: true,
			formatter: function() {
				var out = '<p style="text-transform: uppercase; margin: 5px 9px; font-family: \'Arial\'; font-size: 12px; font-weight: bold; color: #666">' + Highcharts.dateFormat('%e %B %Y', this.x) + '</p><table style="width: 220px; margin: 0 7px 5px">';
				$.each(this.points, function(i, point) {
					var //percentChange = point.point.change,
						seriesColor = point.point.series.color,
						symbol = "";

					//if(this.y > 0) {
						//symbol = "+";
					//}

					out += '<tr><td style="color: ' + seriesColor + '; font-size: 14px; font-family: \'Arial\'; padding: 0 7px 0 0;">' + point.point.series.name + ': </td>' +
						'<td style="text-align: center; background: ' + seriesColor + '; color: white; font-size: 20px; width: 90px; padding: 0 7px; font-family: \'Arial\'">' +
						symbol + Highcharts.numberFormat(this.y, 2) + '</td></tr>';
				});

				out += '</table>';

				return out;
			}
		},
		xAxis: {
			type: 'datetime',
			events: {
				afterSetExtremes: function(e) {
					var minDate = new Date(e.min),
						maxDate = new Date(e.max),
						minPrefix = "",
						maxPrefix = "";
					
					if(minDate.getUTCDate() < 10) {
						minPrefix = "0";
					}
					if(maxDate.getUTCDate() < 10) {
						maxPrefix = "0";
					}
					minDate = minDate.getUTCFullYear() + "-" + (parseInt(minDate.getUTCMonth(),10)+1) + "-" + minPrefix + minDate.getUTCDate();
					maxDate = maxDate.getUTCFullYear() + "-" + (parseInt(maxDate.getUTCMonth(),10)+1) + "-" + maxPrefix + maxDate.getUTCDate();
					
					CC.comparisonTool.changeDates(CC.comparisonTool.chart, minDate, maxDate);
				}
			}
		}
	},
	performAjax: function(successCallback) {
		// Make sure the query object is set before calling this function!!
		var start = new Date();
		$.ajax({
			url: 'updateGraphData',
			type: 'GET',
			data: CC.comparisonTool.query,
			datatype: 'json'
		}).done(function (data) {
			var end = new Date();
			$("#ajaxTimeLog").append($("<ul/>").text("Query time " + (end - start) + "ms"));
			successCallback(data);
			}).fail(function(jqXHR, textStatus) {
			console.log(textStatus);
		});
	},
	selectFund: function(optionElement) {
		var $optionElement = $(optionElement);
		
		// Add fund to query and submit ajax
		CC.comparisonTool.addFund($optionElement);
		
		// Get colour of the new series
		var seriesColour = CC.comparisonTool.chart.options.colors[CC.comparisonTool.seriesColorCount];
		
		// Add fund to "choose datapoints" section
		var tr = $('<tr />');
		tr.attr("data-isin",$optionElement.val())
		tr.attr("data-ticker",$optionElement.attr('data-ticker'))
		
		var fundName = $('<td class="fund">' + $optionElement.attr('data-fundname') + '</td>');
		tr.append(fundName);
		
		td = $('<td class="fund-return" style="background: ' + seriesColour + '"/>');
		input = $('<input type="checkbox" value="fundReturn" checked />');
		
		td.append(input);
		tr.append(td);
		
		td = $('<td class="bm-return"/>');
		input = $('<input type="checkbox" value="benchReturn" />');
		
		td.append(input);
		tr.append(td);
		
		td = $('<td class="nav"/>');
		input = $('<input type="checkbox" value="NAV" />');
		
		td.append(input);
		tr.append(td);
		
		td = $('<td class="remove"><a href="#">X</a></td>');
		
		tr.append(td);
		tr.find('input').change(CC.comparisonTool.toggleDatapoint);
		
		$('.data-types table tbody').append(tr);

		// Remove fund from select
		$optionElement.remove();
	},
	toggleDatapoint: function(event) {
		var checkbox = $(this);
		var isin = checkbox.parents("tr").attr("data-isin");
		var ticker = checkbox.parents("tr").attr("data-ticker");
		var dataType = checkbox.val();
		var enabled = checkbox.prop('checked');
		if (enabled) {
			//add
			CC.comparisonTool.addChartDataPoint(isin, dataType, ticker);
			// Get colour of the new series
			var seriesColour = CC.comparisonTool.chart.options.colors[CC.comparisonTool.seriesColorCount];
			checkbox.parents("td").css('background', seriesColour);
		} else {
			//remove
			CC.comparisonTool.removeChartDataPoint(checkbox, isin, dataType);
		}
	},
	removeFund: function() {
		var $thisRow = $(this).parents('tr'),
		isin = $thisRow.attr('data-isin'),
		deleteI = [],
		optFundName = $thisRow.find('.fund').text(),
		optTicker = $thisRow.attr('data-ticker'),
		optIsin = $thisRow.attr('data-isin');

		for(var i = 0; i< CC.comparisonTool.series.length; i++){
			if (CC.comparisonTool.series[i].isin == isin) {
				CC.comparisonTool.series.splice(i, 1);
				CC.comparisonTool.chart.series[i].remove();
				i--;
			}
		}
		
		var option = $('<option/>');
		option.text(optTicker + " " + optFundName);
		option.attr('data-fundname', optFundName);
		option.attr('data-ticker', optTicker);
		option.attr('value', optIsin);
		
		$('.fund-dropdown select').append(option);
		$(this).parents('tr').remove();
	},
	removeChartDataPoint: function(checkbox, isin, dataType) {
		for(i=0; i< CC.comparisonTool.series.length; i++){
			if (CC.comparisonTool.series[i].isin == isin && CC.comparisonTool.series[i].dataType == dataType) {
				CC.comparisonTool.series.splice(i, 1);
				CC.comparisonTool.chart.series[i].remove();
			}
		}
		checkbox.parents("td").css('background', 'none');
	},
	addFund: function(optionElement) {
		var isin = optionElement.val();
		CC.comparisonTool.addChartDataPoint(isin, 'fundReturn', $(optionElement).attr('data-ticker'));
	},
	addChartDataPoint: function(isin, dataType, displayName) {
		CC.comparisonTool.query.isin = isin;
		
		var minDate = new Date(CC.comparisonTool.chart.xAxis[0].getExtremes().dataMin);
		var maxDate = new Date(CC.comparisonTool.chart.xAxis[0].getExtremes().dataMax);
		var minPrefix = "";
		var maxPrefix = "";
	
		if(minDate.getUTCDate() < 10) {
			minPrefix = "0";
		}
		if(maxDate.getUTCDate() < 10) {
			maxPrefix = "0";
		}
		
		CC.comparisonTool.query.startDate = minDate.getUTCFullYear() + "-" + (parseInt(minDate.getUTCMonth(),10)+1) + "-" + minPrefix + minDate.getUTCDate();;
		CC.comparisonTool.query.endDate = maxDate.getUTCFullYear() + "-" + (parseInt(maxDate.getUTCMonth(),10)+1) + "-" + maxPrefix + maxDate.getUTCDate();;
		CC.comparisonTool.query.dataType = dataType;
		
		CC.comparisonTool.chart.showLoading();
		CC.comparisonTool.performAjax(function(data) {
			if(CC.comparisonTool.seriesColorCount + 1 < CC.comparisonTool.chart.options.colors.length) {
				CC.comparisonTool.seriesColorCount++;
			} else {
				CC.comparisonTool.seriesColorCount = 0;
			}
			CC.comparisonTool.addSeries(CC.comparisonTool.chart, data, displayName);
			CC.comparisonTool.chart.hideLoading();
		});
	},
	addSeries: function(chart, data, displayName) {
		var datatypeStr = "";
		switch(CC.comparisonTool.query.dataType) {
		case "fundReturn":
			datatypeStr = "Fund Return";
			break;
		case "benchReturn":
			datatypeStr = "Benchmark Return";
			break;
		default:
			datatypeStr = CC.comparisonTool.query.dataType;
		}

		var seriesData = [];
		for(var datum in data) {
			seriesData.push([parseInt(datum,10), data[datum][CC.comparisonTool.query.dataType]]);
		}
		
		var series = {
			isin: CC.comparisonTool.query.isin,
			name: displayName + " - " + datatypeStr,
			data: seriesData,
			dataType: CC.comparisonTool.query.dataType
		};
		
		CC.comparisonTool.series.push(series);
		chart.addSeries(series);
	},
	changeDates: function(chart, fromDate, toDate) {
		CC.comparisonTool.chart.showLoading();
		CC.comparisonTool.query.startDate = fromDate;
		CC.comparisonTool.query.endDate = toDate;
		
		var isinDataTypes = {};
		
		for (var i = 0; i < chart.series.length; i++) {
			if(chart.series[i].name !== "Navigator") {
				var isin = CC.comparisonTool.series[i].isin;
				if (typeof isinDataTypes[isin] == 'undefined') {
					isinDataTypes[isin] = [];
				}
				isinDataTypes[isin].push(CC.comparisonTool.series[i].dataType);
			}
		}
		
		for (var isin in isinDataTypes) {
			CC.comparisonTool.query.isin = isin;
			CC.comparisonTool.query.dataType = isinDataTypes[isin].join();
			CC.comparisonTool.performAjax(function(data) {
				CC.comparisonTool.updateSeries(CC.comparisonTool.chart, CC.comparisonTool.query.isin, data);
				CC.comparisonTool.chart.hideLoading();
			});
		}
		
	},
	updateSeries: function(chart, isin, data) {
		// Set the data of a set series, for example when selecting a new date range
		var seriesData = {};
		var dataTypes = CC.comparisonTool.query.dataType.split(",");
		for (var i = 0; i < dataTypes.length; i++) {
			seriesData[dataTypes[i]] = [];
			for(var datum in data) {
				seriesData[dataTypes[i]].push([parseInt(datum,10), data[datum][dataTypes[i]]]);
			}
		}
		for(var i = 0; i< CC.comparisonTool.series.length; i++){
			if (CC.comparisonTool.series[i].isin == isin) {
				chart.series[i].setData(seriesData[CC.comparisonTool.series[i].dataType]);
			}
		}	
	},
	initEventHandlers: function() {
		// Add any click/change events here
		$('body').on('click', 'a[href="#"]', function(e) {
			e.preventDefault();
		});
		
		$('.data-types').on('click', '.remove a', CC.comparisonTool.removeFund);
		
		//Setup the data type toggle handler for the first fund
		$('.data-types table tbody input').change(CC.comparisonTool.toggleDatapoint);
	},
	initChart: function(options) {
		
		var options = {
			series: [{
				data: CC.comparisonTool.series[0].data.sort(),
				name: CC.comparisonTool.series[0].name
			}],
		};
		
		if(CC.comparisonTool.separateNavigator.data.length > 0) {
			options.navigator = {
				series: CC.comparisonTool.separateNavigator
			}
		}
			
		// Merge these custom options with the defaults
		var chartOptions = $.extend(true, {}, CC.comparisonTool.defaultOptions, options);

		// Call Highstock plugin
		CC.comparisonTool.chart = new Highcharts.StockChart(chartOptions);
	},
	init: function() {
		
		CC.comparisonTool.initChart();
		$('.fund-dropdown select').combobox();
		CC.comparisonTool.initEventHandlers();
		
		// Tooltips
		$(document).tooltip();
	}
};

$(document).ready(function() {
	CC.comparisonTool.init();
});